package com.yunhe.tianhe.service.premission.impl;

import com.yunhe.commons.dto.Pagedao;
import com.yunhe.commons.dto.TreeNode;
import com.yunhe.tianhe.dao.permission.ResourceDao;
import com.yunhe.tianhe.dao.permission.RoleDao;
import com.yunhe.tianhe.entity.premission.Resource;
import com.yunhe.tianhe.entity.premission.Role;
import com.yunhe.tianhe.service.premission.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author LeiPeifeng
 * @version V1.0
 * @date 2017/11/29 0029 17:33
 * @Description: 实现RoleService接口
 */
@Service
public class RoleServiceImpl implements RoleService{

    @Autowired
    private RoleDao roleDao;
    @Autowired
    private ResourceDao resourceDao;

//
    public  void saveRoleResource(Role role,String ids){
        String[] split = ids.split ( "," );
        for (String resourceid:split){
            roleDao.saveRoleResource ( role.getRoleid (),new Long(resourceid) );
        }
    }

    @Override
    public void save(Role role,String ids) {
        roleDao.save ( role );
        saveRoleResource ( role,ids );
    }

    @Override
    public void update(Role role,String ids) {
        roleDao.update ( role );
        roleDao.deletedRoleResource ( role.getRoleid () );
        saveRoleResource ( role,ids );
    }

    @Override
    public void deleted(String ids) {
        String[] split = ids.split ( "," );
        for (String roleid:split){
            roleDao.deleted ( new Long ( roleid ) );
        }
    }

    @Override
    public Role find(Long roleid) {
        return roleDao.find ( roleid );
    }

    @Override
    public List<Role> findlist(Role role) {
        return roleDao.findlist ( role );
    }

    @Override
    public Pagedao<Role> findpage(int offset, int limit) {
        Pagedao<Role> pagedao = new Pagedao<> ();
        List<Role> findpage = roleDao.findpage ( offset, limit );
        pagedao.setRows ( findpage );
        return pagedao;
    }

    @Override
    public List<TreeNode> findtree(Long roleid) {
        List<Resource> findlist = resourceDao.findlist ( null );//查找所有的权限
        List<Long> longs = roleDao.findPermi ( roleid ); //查询角色所拥有的权限
        List<TreeNode> treeNode = new ArrayList<> ();
        if (null != findlist) {
            for (Resource resource : findlist) {
                TreeNode treeNode1 = new TreeNode ( resource.getPermisid (), resource.getParentid (), resource.getPermisname () );
                if (longs.contains ( resource.getPermisid () )){
                    treeNode1.setChecked ( Boolean.TRUE );//选中该权限
                }
                treeNode.add ( treeNode1 );
            }
        }
        return treeNode;
    }


}
